package com.easyUploader.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easyUploader.entity.dao.FileChunk;
import com.easyUploader.entity.vo.FileChunkVo;
import com.easyUploader.mapper.FileChunkMapper;
import com.easyUploader.service.IFileChunkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import static com.easyUploader.entity.factory.FileChunkFactory.FILE_CHUNK_CONVERTER;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月29日
 */
@Service
@Slf4j
public class FileChunkServiceImpl extends ServiceImpl<FileChunkMapper, FileChunk> implements IFileChunkService {
    private final Executor CLEAN_THREAD=Executors.newCachedThreadPool();

    @Override
    public List<FileChunk> findByMd5(String fileIdentifier) {
        return list(new QueryWrapper<FileChunk>().eq("file_identifier",fileIdentifier));
    }

    @Override
    public void saveFileChunk(FileChunkVo fileChunkVo, Consumer<FileChunkVo> saveToLocalStorage) {
        FileChunk fileChunk = FILE_CHUNK_CONVERTER.toFileChunk(fileChunkVo);
        save(fileChunk);
        //当文件分片完整上传完成，存一份在LocalStorage表中
        if(fileChunkVo.allChunkReady(this)){
            log.info("当前文件数据全部上传完毕!");
            saveToLocalStorage.accept(fileChunkVo);
            //异步线程将当前文件在分片表中的分片信息清除
            clearChunkInfoAsync(fileChunkVo);
        }
    }

    private void clearChunkInfoAsync(FileChunkVo fileChunkVo) {
        CompletableFuture.runAsync(()->{
             remove(new QueryWrapper<FileChunk>().eq("file_identifier", fileChunkVo.getFileIdentifier()));
             log.info("{}文件相关持久化分片信息已经清除完毕", fileChunkVo.getFileName());
        }, CLEAN_THREAD);
    }

}
